package com.caocaog.market.controller;

import com.caocaog.market.common.PushCommon;
import com.caocaog.market.entity.PushMessageTemplate;
import com.caocaog.market.service.PushMessageTemplateService;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.res.TaskIdDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.util.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.CheckFailedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(value = "push", tags = "推送测试")
@RequestMapping("/api/push")
public class PushController {

    private PushCommon pushCommon;
    private PushMessageTemplateService pushMessageTemplateService;

    @PostMapping("/createMessage")
    @ApiOperation(value = "创建消息")
    public Result<Object> createMessage(Integer pushMessageTemplateId) {
        PushMessageTemplate pushMessageTemplate = this.pushMessageTemplateService.getPushMessageTemplateById(pushMessageTemplateId);
        return Result.OK(this.pushCommon.createMessage(pushMessageTemplate));
    }

    @PostMapping("/pushSingleByAlias")
    @ApiOperation(value = "根据别名单推送")
    public Result<Object> pushSingleByAlias(Integer pushMessageTemplateId, String alias) {
        PushMessageTemplate pushMessageTemplate = this.pushMessageTemplateService.getPushMessageTemplateById(pushMessageTemplateId);
        return Result.OK(this.pushCommon.toSingleByAlias(pushMessageTemplate.putPayload("type", pushMessageTemplate.getId()), alias));
    }

    @PostMapping("/pushListByAlias")
    @ApiOperation(value = "根据别名群推送")
    public Result<Object> push(Integer pushMessageTemplateId, String alias) {
        PushMessageTemplate pushMessageTemplate = this.pushMessageTemplateService.getPushMessageTemplateById(pushMessageTemplateId);
        // 批量群推都需要先创建消息
        ApiResult<TaskIdDTO> apiResult = this.pushCommon.createMessage(pushMessageTemplate.putPayload("type", pushMessageTemplate.getId()));
        if (!apiResult.isSuccess()) throw new CheckFailedException("创建消息失败-> " + apiResult.getMsg());
        return Result.OK(this.pushCommon.toListByAlias(
                pushMessageTemplateId,
                apiResult.getData().getTaskId(),
                StringUtils.split(alias, ',')
        ));
    }


    @Autowired(required = false)
    public void setPushCommon(PushCommon pushCommon) {
        this.pushCommon = pushCommon;
    }

    @Autowired
    public void setPushMessageTemplateService(PushMessageTemplateService pushMessageTemplateService) {
        this.pushMessageTemplateService = pushMessageTemplateService;
    }
}
